package com.heny.nc;

import com.heny.demo.common.CommonErrorCode;
import com.heny.demo.common.CommonException;
import com.heny.nc.model.NCModel;
import com.heny.nc.model.SaveTypeEnum;
import com.heny.nc.service.SaveDataProcessorContext;
import lombok.Data;
import ucar.ma2.Array;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author litao.cc
 * @version NCFileHandler.java v0.1 t2025/4/26 17:57
 * @date 2025/4/26 17:57
 * @description nc文件处理器
 */
@Data
public class NCFileHandler {
    // 文件名称模板
    private static final String BASE_NAME = "NMC_HENAN_RH-AVG_L2M_G005_%s_H24_H1_";

    private String ncFilePath;
    private String savePath;
    private SaveTypeEnum type;

    private String baseFileName;
    private String time;
    private Map<Integer, List<NCModel>> data;


    private List<String> filePathList;

    NCFileHandler(String ncFilePath, String savePath, SaveTypeEnum type){
        this.ncFilePath = ncFilePath;
        this.savePath = savePath;
        this.type = type;
    }

    public void apply(){
        read();
        SaveDataProcessorContext context = new SaveDataProcessorContext(
                this.data,
                this.savePath,
                this.type.name(),
                this.baseFileName
        );
        context.execute();
        this.filePathList = context.getFilePathList();
    }

    private void read(){
        try (NetcdfFile ncFile = NetcdfFile.open(this.ncFilePath)) {
            Variable lonVar = ncFile.findVariable("lon");
            Variable latVar = ncFile.findVariable("lat");
            Variable timeVar = ncFile.findVariable("time");
            Variable dtimeVar = ncFile.findVariable("dtime");
            Variable dataVar = ncFile.findVariable("data"); // 数据
            Array lonArray = lonVar.read();
            Array latArray = latVar.read();
            Array timeArray = timeVar.read();
            Array dtimeArray = dtimeVar.read();
            Array dataArray = dataVar.read();

            this.time = timeArray.getObject(0).toString();
            this.baseFileName = buildBaseName(this.time);
            List<ucar.nc2.Dimension> dimensions = dataVar.getDimensions();
            int dtimeLen = dimensions.get(3).getLength();
            int latLen = dimensions.get(4).getLength();
            int lonLen = dimensions.get(5).getLength();

            this.data = new HashMap<>(dtimeLen);
            // 遍历数据
            for (int t = 0; t < dtimeLen; t++) {

                Integer dtimeVal = dtimeArray.getInt(t);
                this.data.put(dtimeVal,new ArrayList<>(latLen));
                for (int y = 0; y < latLen; y++) {
                    double lat = latArray.getDouble(y);
                    for (int x = 0; x < lonLen; x++) {
                        double lon = lonArray.getDouble(x);
                        double temp = dataArray.getDouble(t * latLen * lonLen + y * lonLen + x);
                        String line = String.format("%f,%f,%s,%f%n", lon, lat, dtimeVal, temp);
                        this.data.get(dtimeVal).add(new NCModel(lon,lat,temp));
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    // 工具
    private static String buildBaseName(String time) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date date = inputFormat.parse(time);
            time = outputFormat.format(date);
            return String.format(BASE_NAME, time);
        } catch (ParseException e) {
           throw new CommonException(CommonErrorCode.SYSTEM_ERROR,"时间转换异常");
        }
    }

}
